package com.zwy.ubts.service.impl;


import com.zwy.ubts.bean.User;
import com.zwy.ubts.dao.UserDao;
import com.zwy.ubts.service.BaseService;
import com.zwy.ubts.service.UserService;
import com.zwy.ubts.utils.DateUtil;
import com.zwy.ubts.utils.Md5;
import com.zwy.ubts.utils.MybatisUtils;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.ibatis.session.SqlSession;

import java.util.ArrayList;
import java.util.List;

/**
 * @Author zwy
 * @Description:
 * @Date Created in 14:03 2022/12/23
 */

public class UserServiceImpl extends BaseService<UserDao> implements UserService {

    @Override
    public User login(User user) {
        // 因为在注册时采用 MD5 进行密码的加密操作，所有在验证时就不用能原始的密码来进行
        // 需要使用统一的加密规则进行密码的加密，然后再进行密码的验证
        user.setUserPass(Md5.md5(user.getUserPass()));
        System.out.println("user:"+user);
        User login = baseDao.login(user);
        return login;
    }

    @Override
    public Integer addUser(User user) {
        // 进行密码的加密 -- MD5实现密码加密,需要下载对应的 jar 包，一般是将密码转换为一个 16 位的字符串
        user.setUserPass(Md5.md5(user.getUserPass()));
        user.setUserRole(1);
        user.setUserMoney(0);
        user.setUserCreateTime(DateUtil.getCurrentDate());
        //user.setUserImg("ys_head2.jpg");
        Integer integer = baseDao.addUser(user);
        commit();
        return integer;
    }

    @Override
    public Boolean isHaveUser(String username) {
        if(baseDao.selectUserByName(new User(username,null)) == null){
            return false;
        }
        return true;
    }

    @Override
    public Boolean isHaveEMail(String email) {
        User user = new User();
        user.setUserEmail(email);

        if(baseDao.selectUserByEMail(user)== null){
            return false;
        }
        return true;    }

    @Override
    public User getUserByEMail(String email) {
        User user = new User();
        user.setUserEmail(email);
        return baseDao.selectUserByEMail(user);
    }

    @Override
    public User selectUserById(Integer id) {
        return baseDao.selectUserById(new User(id));
    }

    @Override
    public Integer updatePassword(String email,String userpassword) {
        User user = new User();
        user.setUserEmail(email);
        if(!isHaveEMail(email)){//邮箱不存在
            return -1;
        }
        user.setUserPass(Md5.md5(userpassword));
        Integer integer = baseDao.updatePassword(user);
        commit();
        return integer;
    }

    @Override
    public Integer updateUserMoneyById(Integer userId, Float money) {
        baseDao.updateUserMoneyById(userId,money);
        commit();
        return 1;
    }

    @Override
    public List<User> selectUser() {
        return baseDao.selectUser();
    }

    @Override
    public List<User> selectUserByRole(Integer userRole) {
        return baseDao.selectUserByRole(userRole);
    }


}
